package net.xdclass.component;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.SmsConfig;
import net.xdclass.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author ：zhouyang
 * @date ：Created in 2022/5/6 10:11
 * @modified By：
 * @version: $
 */
@Component
@Slf4j
public class SmsComponent {

    private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;


    public void send (String to ,String templateId,String value){
        long currentTimestamp = CommonUtil.getCurrentTimestamp();
        String url = String.format(URL_TEMPLATE,to,templateId,value);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization","APPCODE "+ smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity(headers);
         ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        long currentTimestamp1 = CommonUtil.getCurrentTimestamp();
        long t =  currentTimestamp1-currentTimestamp;
        log.info("消耗时间{}",String.valueOf(t));
         log.info("url={},body={}",url,exchange.getBody());
         if (exchange.getStatusCode() == HttpStatus.OK){
             log.info("发送短信验证码成功");
         }else {
             log.error("发送短信验证码失败：{}",exchange.getBody());
         }


    }

}
